import { defineStore } from 'pinia'
import { $get, $post } from '@/lib/plugin/Aegis'
import { IRole } from '@/interface'

type RootState = {
  summary: {
    roles:IRole[];
    articlesTotal:number;
    sendStarsTotal:number;
    receiveStarsTotal:number;
    sendCommentsTotal:number;
    receiveCommentsTotal:number;
    qq_users: any[];
    github_users: any[];
  } | null;
  userInfo: {
  } | null;
  token: {
  } | null;
};

export const userStore = defineStore('user', {
  state: () => {
    return {
      summary: {},
      userInfo: null,
      token: null
    } as RootState
  },
  getters: {},
  actions: {
    logout () {
      localStorage.removeItem('token')
      this.userInfo = null
    },
    setToken (res: any): void {
      if (res === null) {
        localStorage.removeItem('token')
      } else {
        localStorage.setItem('token', res)
      }
      this.token = res
    },
    setUserInfo (res: any): void {
      this.userInfo = res
    },
    setSummary (res: any): void {
      this.summary = res
    },
    async login (payload: any) {
      try {
        const data = await $post('user/login', {
          ...payload,
          exp: 24
        })
        if (data === null) {
          localStorage.removeItem('token')
        } else {
          localStorage.setItem('token', data)
        }
        this.token = data
        return Promise.resolve(data)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    async getUserInfo () {
      try {
        const { data } = await $get('user/get_user_info')
        this.userInfo = data
        this.summary = {
          articlesTotal: data.articles_total,
          receiveCommentsTotal: data.receive_comments_total,
          sendCommentsTotal: data.send_comments_total,
          receiveStarsTotal: data.receive_stars_total,
          sendStarsTotal: data.send_stars_total,
          qq_users: data.qq_users,
          github_users: data.github_users,
          roles: data.roles
        }
        return Promise.resolve(true)
      } catch (error) {
        console.log(error)
        return Promise.reject(error)
      }
    }
  }
})
